package com.aistar.user.interceptor;


import com.aistar.common.vo.Result;
import com.aistar.common.vo.StatusCode;
import com.aistar.user.entity.User;
import com.aistar.user.service.IUserService;
import com.aistar.user.util.TokenUtil;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by js on 2019/6/27.
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        System.out.println("request....");
        Result result=null;
        ServletOutputStream out=response.getOutputStream();

        //获取请求头中的token
        String token=request.getHeader("Authorization");
        System.out.println(token);
        if (null!=token){
            token=token.substring(7);
            System.out.println(token);
            if (!token.equals("null")){
                Claims claims=tokenUtil.paraseToken(token);
                System.out.println(claims);
                if (null!=claims){
                    request.setAttribute("claims",claims);
                }
            }

        }

//        //获取头请求中的token
//        String token=request.getHeader("Authorization").substring(7);
//        System.out.println(token);
//
//        if (null==token){
//            result=new Result(false,StatusCode.ERROR,"无token,请重新登录");
//            String jsonStr=JSON.toJSONString(result);
//            out.println(jsonStr);
//            return false;
//        }
//
//        //拿到token后,核验token是否正确
//
//        //判断token的时间是否过期
//        //获取token中的过期时间
//        Date date=tokenUtil.paraseToken(token).getIssuedAt();
//
//        //获得token中的id
//        String id=tokenUtil.paraseToken(token).getId();
//
//        //根据id拿到对象
//        User user=iUserService.findById(id);
//
//        if (null==user){
//            result =new Result(false,StatusCode.LOGINERROR,"信息失效 登录失败");
//            String jsonStr=JSON.toJSONString(result);
//            out.println(jsonStr);
//            return false;
//        }



        return true;
    }
}
